package com.zxtc.wh.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.File;
import java.io.IOException;
import java.io.Reader;

/**
 * myBatis获取的工具类
 */
public class MybatisUtils {

    //    内部静态类形式的单例实现
    private final static class SingletonDevelopment {
        private static SqlSessionFactory sessionFactory;

        static {
            final String resource = "mybatis-config.xml";

            try {
                Reader reader = Resources.getResourceAsReader(resource);
                //使用开发环境配置构建工厂
                sessionFactory = new SqlSessionFactoryBuilder().build(reader, "development");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static SqlSession getInstance() {
        return SingletonDevelopment.sessionFactory.openSession();
    }

    public static SqlSession getDebugInstance() {
        final String resource = "mybatis-config.xml";
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //使用开发环境配置构建工厂
        SqlSessionFactory debug = new SqlSessionFactoryBuilder().build(reader, "debug");
        return debug.openSession();
    }

}
